import React, { createContext, useState } from "react";
import classNames from "classnames";
import TabItem from "./tabItem";
import { TabItemProps } from "./tabItem";

type SelectCallback = (selectedIndex: string | undefined) => void;
type BackCallback = (children: React.ReactNode) => void;

type TabsMode = "horizontal" | "vertical";

export interface TabsProps {
  defaultIndex?: string;
  className?: string;
  style?: React.CSSProperties;
  mode?: TabsMode;
  child?: React.ReactNode;
  onSelect?: SelectCallback;
}

interface ITabItem {
  index?: string;
  onSelect: SelectCallback;
  mode?: TabsMode;
  onBack: BackCallback;
}

export const TabsContenx = createContext<ITabItem>({
  index: "0",
  onBack: () => {},
  onSelect: () => {},
});

const Tabs: React.FC<TabsProps> = (props) => {
  const {
    defaultIndex,
    className,
    children,
    style,
    mode,
    child,
    onSelect,
  } = props;
  const [currentActive, setActive] = useState(defaultIndex);
  const [currentChild, setChild] = useState(child);

  const handleClick = (index: string | undefined) => {
    setActive(index);
    if (onSelect) {
      onSelect(index);
    }
  };

  const handleCallback = (child: React.ReactNode) => {
    setChild(child);
  };
  const passedContext: ITabItem = {
    index: currentActive ? currentActive : defaultIndex,
    onSelect: handleClick,
    mode,
    onBack: handleCallback,
  };
  const classes = classNames("zs-tabs", {
    "zs-tabs-vertical": mode === "vertical",
    "zs-tabs-horizontal": mode !== "vertical",
  });

  const renaderChildren = () => {
    return React.Children.map(children, (child, index) => {
      const childElement = child as React.FunctionComponentElement<
        TabItemProps
      >;
      const { displayName } = childElement.type;
      if (displayName === "TabItem") {
        return React.cloneElement(childElement, {
          index: "tab-" + index.toString(),
        });
      } else {
        console.error(
          "Warning:Tabs has a child which is not a TabItem component."
        );
      }
    });
  };

  return (
    <div style={style} className={className}>
      <ul className={classes}>
        <TabsContenx.Provider value={passedContext}>
          {renaderChildren()}
        </TabsContenx.Provider>
      </ul>
      <div className="zs-tab-content">{currentChild}</div>
    </div>
  );
};

TabItem.displayName = "TabItem";

Tabs.defaultProps = {
  defaultIndex: "tab-0",
  mode: "horizontal",
  child: "",
};

export default Tabs;
